package com.booksystem.campuslibrarymanagementsystem.controller.user;


import com.booksystem.campuslibrarymanagementsystem.commen.request.userquest.BookBorrowrequst.*;
import com.booksystem.campuslibrarymanagementsystem.commen.result.Result;
import com.booksystem.campuslibrarymanagementsystem.commen.result.userresuilt.ApprovalList;
import com.booksystem.campuslibrarymanagementsystem.entity.BooksTable;
import com.booksystem.campuslibrarymanagementsystem.entity.BorrowApprovalsTable;
import com.booksystem.campuslibrarymanagementsystem.service.BorrowApprovalsTableService;
import com.booksystem.campuslibrarymanagementsystem.utils.CodeUtil;
import com.booksystem.campuslibrarymanagementsystem.utils.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Map;


@RequestMapping("/User")
@Api(tags = "图书借阅")
@RestController
public class BookBorrowController {

    @Autowired
    BorrowApprovalsTableService borrowApprovalsTableService;
    /*
     图书借阅
    1，输入账户id（学号）,图书id
    2,自动生成当前借阅时间
    3，通过bookid查找图书，确认图书借出数量和总数,比较，
    4，比较图书借出数量 < 总数 ，判断是否图书不可用或借出数量不足
    5，计算过期时间（在当前时间加借阅期限加30天）
    6,// 检查该用户是否已经借阅了这本书，并且借阅状态为“已通过”,借阅时间是否大于过期时间
    如果用户有未到期的借阅记录，则不允许再次借阅。
    7，更新图书表的借出数量-1，借阅成功
     */
    @PostMapping("/bookBorrow")
    @ApiOperation(value = "图书借阅",notes = "通过账户id,图书id进行借阅图书")
    public Result  BookBorrow (@RequestBody BorrowApproval borrowApproval){
        Map<String, Object> parsed = JwtUtil.tokenPre(borrowApproval.getToken());
        if (parsed != null) {
            Object identity = parsed.get("identity");
            Object account = parsed.get("account");
            if (identity.equals("user")) {
                int bookid =borrowApproval.getBookid();//图书id
                String time = CodeUtil.codeGet();//自动生成当前借阅时间
                if (bookid <= 0) {
                    // 如果bookid不是一个正数，则认为它是无效的
                    System.out.println("Invalid book ID: " + bookid);
                    return Result.fail("无效的图书ID");
                }

                //检查图书id是否存在
                BooksTable aa = borrowApprovalsTableService.aaa(bookid);
                if(aa==null){
                    return Result.fail(String.format("该图书不存在，无法借阅该图书：%s", bookid));
                }
                // 检查该用户是否已经借阅了这本书
                List<BorrowApprovalsTable> existingBorrow = borrowApprovalsTableService.existsByAccountAndBookidi((String) account, bookid);
                if (existingBorrow != null && !existingBorrow.isEmpty()) {
                    // 遍历找到的所有借阅记录
                    for (BorrowApprovalsTable entry : existingBorrow) {
                        // 如果状态为“已通过”
                        if ("已通过".equals(entry.getApprovalstate())) {
                            // 直接返回失败结果，不允许再次借阅
                            return Result.fail(String.format("您已经借阅过这本书：%s,该图书已通过", bookid));
                        }
                        // 检查借阅记录是否已经过期
                        if (entry.getExpirationdate().isBefore(LocalDate.now())) {
                            // 如果借阅记录已经过期，也返回失败结果，不允许再次借阅
                            return Result.fail(String.format("您之前借阅的这本书：%s 已经过期，请先删除之前的借阅记录。", bookid));
                        }
                    }
                }


                // 查找图书，确认图书借出数和总数
                Approval book = borrowApprovalsTableService.queryid(bookid);
                if (book == null || !book.canBeBorrowed()) {
                    return Result.fail("图书不可用或借出数量不足");
                }else {
                    // 计算过期时间
                    LocalDate borrowTime = LocalDate.now();
                    LocalDate expirationDate = borrowTime.plus(30, ChronoUnit.DAYS); // 假设借阅期限是30天

                    BorrowApprovalsTable hh = new BorrowApprovalsTable();
                    hh.setBookid(bookid);
                    hh.setBorrowdate(time);
                    hh.setExpirationdate(expirationDate);
                    hh.setApprovalstate("未审批");
                    hh.setAccount((String) account);
                    boolean c =borrowApprovalsTableService.save(hh);
                    if(c){
                        // 更新图书的借出数量
                        book.setAvailablecopies(book.getAvailablecopies() - 1);
                        borrowApprovalsTableService.updatebook(book);
                        return Result.success("借阅成功，过期时间为：" + expirationDate,1);
                    }
                    return Result.fail("借阅失败");

                }
            } else {
                return Result.fail("身份权限不足");
            }
        } else {
            return Result.fail("请输入正确token值");
        }
    }


    /*
  1，通过判断状态（未通过，通过） 可以查看所有未通过的列表和所有通过列表
  2，输入除状态（未通过，通过）外就会报无效状态
   */
    @PostMapping("/borrowlisttstatus")
    @ApiOperation(value = "是否通过，已拒绝图书借阅列表", notes = "可以查看所有未通过的列表和所有通过的借阅图书列表")
    public Result<List<ApprovalList>> selectBookBorrowlist (@RequestBody BorrowApprovallist borrowApprovallist) {
        Map<String, Object> parsed = JwtUtil.tokenPre(borrowApprovallist.getToken());
        if (parsed != null) {
            Object identity = parsed.get("identity");
            Object account = parsed.get("account");
            if (identity.equals("user")) {
                String statu = borrowApprovallist.getApprovalstate();//借阅状态
                // 判断状态是否为空
                if (statu == null || statu.trim().isEmpty()) {
                    List<ApprovalList>  aa = borrowApprovalsTableService.selectByaccount((String) account);
                    if (aa.isEmpty()) {
                        // 提供更具体的错误信息，说明是基于哪几个条件没有找到匹配的图书
                        return Result.fail(String.format("没有找到基于账户id：%s", (String) account));
                    } else {
                        return Result.success(aa, 1);
                    }
                }
                List<ApprovalList> statusList = null;
                if ("已通过".equals(statu)) {
                    statusList = borrowApprovalsTableService.returnliststatus((String) account, statu);
                } else if ("未通过".equals(statu)) {
                    statusList = borrowApprovalsTableService.returnliststatus((String) account, statu);
                } else if ("未审批".equals(statu)) {
                    statusList = borrowApprovalsTableService.returnliststatus((String) account, statu);
                }else {
                    return Result.fail("无效的状态值");
                }

                // 检查列表是否为空
                if (statusList.isEmpty()) {
                    return Result.fail("没有找到账户id为 '" + (String) account + "状态为 '" + statu + "' 的借阅记录");
                } else {
                    return Result.success(statusList, statusList.size());
                }

            } else {
                return Result.fail("身份权限不足");
            }
        } else {
            return Result.fail("请输入正确token值");
        }
    }
    @PostMapping("/borrowlist")
    @ApiOperation(value = "查看所有借阅列表",notes = "账户id，进行查看自己的所有借阅列表")
    public Result<List<ApprovalList>> borrowList(@RequestBody Borrowlist borrowlist) {
        Map<String, Object> parsed = JwtUtil.tokenPre(borrowlist.getToken());
        if (parsed != null) {
            Object identity = parsed.get("identity");
            Object account = parsed.get("account");
            if (identity.equals("user")) {
                List<ApprovalList>  aa = borrowApprovalsTableService.selectByaccount((String) account);
                if (aa.isEmpty()) {
                    // 提供更具体的错误信息，说明是基于哪几个条件没有找到匹配的图书
                    return Result.fail(String.format("该账户id没有借阅图书：%s？,请重新借阅！！", (String) account));
                } else {
                    return Result.success(aa, 1);
                }
            } else {
                return Result.fail("身份权限不足");
            }
        } else {
            return Result.fail("请输入正确token值");
        }
    }

    @PostMapping("/deleteBorrow")
    @ApiOperation(value = "删除借阅书籍",notes = "账户id，借阅id进行删除该账户下该图书的借阅记录")
    public Result deleteCollection(@RequestBody DeletBorrow deletBorrow) {
        Map<String, Object> parsed = JwtUtil.tokenPre(deletBorrow.getToken());
        if (parsed != null) {
            Object identity = parsed.get("identity");
            Object account = parsed.get("account");
            if (identity.equals("user")) {
                int  bookid =deletBorrow.getRecordid();  //借阅id
                int hh = borrowApprovalsTableService.deleteByAccountAndBookid((String) account, bookid);
                // 首先检查该用户是否已经收藏了这本书
                if (hh>0) {
                    return  Result.success("成功删除该图书借阅记录",1);
                }
                return Result.fail(String.format("没有该图书的借阅记录：%s", bookid));
            } else {
                return Result.fail("身份权限不足");
            }
        } else {
            return Result.fail("请输入正确token值");
        }
    }


}
